import { useMemo, useState } from 'react';
import { Badge, Button, Card, Empty, Input, Select, Space, Tag, Tooltip, Pagination, Skeleton, Segmented, message, Modal, Descriptions } from 'antd';
import { UserOutlined, ClockCircleOutlined, StarOutlined, MailOutlined, PhoneOutlined, BookOutlined, TeamOutlined, TrophyOutlined } from '@ant-design/icons';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { getApprovedCourses, getMyCourses, selectCourse, getTeacherByName } from '../../api/student';
import { hasConflict } from './time';

export default function CoursePool() {
  const qc = useQueryClient();
  const { data: pool = [], isLoading: l1 } = useQuery({ queryKey: ['courses', 'approved'], queryFn: getApprovedCourses });
  const { data: mine = [], isLoading: l2 } = useQuery({ queryKey: ['me', 'courses'], queryFn: getMyCourses });

  const [q, setQ] = useState('');
  const [weekday, setWeekday] = useState<number | undefined>(undefined);
  const [teacher, setTeacher] = useState<string | undefined>(undefined);
  const [credit, setCredit] = useState<number | undefined>(undefined);
  const [sort, setSort] = useState<'default' | 'remaining' | 'time'>('default');
  const [page, setPage] = useState(1);
  const pageSize = 6;
  const [teacherModalVisible, setTeacherModalVisible] = useState(false);
  const [selectedTeacherName, setSelectedTeacherName] = useState<string>('');

  const { data: teacherInfo, isLoading: teacherLoading } = useQuery({
    queryKey: ['teacher', selectedTeacherName],
    queryFn: () => getTeacherByName(selectedTeacherName),
    enabled: teacherModalVisible && !!selectedTeacherName,
  });

  const handleTeacherClick = (teacherName: string) => {
    setSelectedTeacherName(teacherName);
    setTeacherModalVisible(true);
  };

  const mutation = useMutation({
    mutationFn: (courseId: string) => selectCourse(courseId),
    onSuccess: async () => {
      message.success('选课成功');
      await Promise.all([
        qc.invalidateQueries({ queryKey: ['courses', 'approved'] }),
        qc.invalidateQueries({ queryKey: ['me', 'courses'] }),
      ]);
    },
    onError: (e: any) => message.error(e.message || '选课失败'),
  });

  const selectedIds = useMemo(() => new Set(mine.map(m => m.id)), [mine]);

  const filtered = useMemo(() => {
    let list = pool.filter(c => {
      const byQ = q ? c.name.includes(q) : true;
      const byT = teacher ? c.teacherName.includes(teacher) : true;
      const byW = weekday ? c.timeSlots.some(t => t.dayOfWeek === weekday) : true;
      const byC = credit ? (c.credit === credit) : true;
      return byQ && byT && byW && byC;
    });
    if (sort === 'remaining') {
      list = list.slice().sort((a, b) => (a.capacity - a.enrolledCount) - (b.capacity - b.enrolledCount));
    } else if (sort === 'time') {
      const toMinutes = (s: string) => {
        const [h, m] = s.split(':').map(Number);
        return h * 60 + m;
      };
      list = list.slice().sort((a, b) => {
        const ta = Math.min(...a.timeSlots.map(t => t.dayOfWeek * 24 * 60 + toMinutes(t.start)));
        const tb = Math.min(...b.timeSlots.map(t => t.dayOfWeek * 24 * 60 + toMinutes(t.start)));
        return ta - tb;
      });
    }
    return list;
  }, [pool, q, teacher, weekday, credit, sort]);

  const paged = useMemo(() => {
    const start = (page - 1) * pageSize;
    return filtered.slice(start, start + pageSize);
  }, [filtered, page]);

  if (l1 || l2) {
    return (
      <div className="grid md:grid-cols-3 gap-4">
        {Array.from({ length: 6 }).map((_, i) => (
          <Card key={i}>
            <Skeleton active paragraph={{ rows: 3 }} />
          </Card>
        ))}
      </div>
    );
  }
  if (!pool.length) return <Empty description="暂无课程" />;

  return (
    <div>
      <div className="mb-4 grid grid-cols-1 md:grid-cols-5 gap-3">
        <Input placeholder="搜索课程名..." value={q} onChange={e => { setPage(1); setQ(e.target.value); }} />
        <Select
          allowClear
          placeholder="上课时间"
          value={weekday}
          onChange={(v)=>{ setPage(1); setWeekday(v); }}
          options={[1,2,3,4,5,6,7].map(d => ({ value: d, label: `周${d}` }))}
        />
        <Input placeholder="任课教师" value={teacher} onChange={e => { setPage(1); setTeacher(e.target.value); }} />
        <Select allowClear placeholder="学分" value={credit} onChange={(v)=>{ setPage(1); setCredit(v); }} options={[1,2,3,4,5,6].map(c=>({value:c,label:`${c}学分`}))} />
        <Segmented value={sort} onChange={(v)=>setSort(v as any)} options={[{label:'默认', value:'default'},{label:'剩余名额', value:'remaining'},{label:'上课时间', value:'time'}]} />
      </div>

      <div className="grid md:grid-cols-3 gap-4">
        {paged.map(c => {
          const full = c.enrolledCount >= c.capacity;
          const already = selectedIds.has(c.id);
          const conflict = hasConflict(mine, c);
          const disabled = full || already || conflict;

          return (
            <Card
              key={c.id}
              title={<Space>
                <span className="font-semibold">{c.name}</span>
                <Tag color="blue">{c.credit}学分</Tag>
              </Space>}
              extra={<Badge status={full ? 'error' : 'processing'} text={`${c.enrolledCount}/${c.capacity}`} />}
            >
              <div className="text-slate-500 mb-2">
                <UserOutlined className="mr-1" />
                教师：
                <span 
                  className="text-blue-600 hover:text-blue-800 cursor-pointer hover:underline ml-1"
                  onClick={() => handleTeacherClick(c.teacherName)}
                >
                  {c.teacherName}
                </span>
              </div>
              <div className="mb-1 space-x-2">
                {c.timeSlots.map((t, i) => (
                  <Tag key={i}><ClockCircleOutlined className="mr-1" />{`周${t.dayOfWeek} ${t.start}-${t.end}`}</Tag>
                ))}
              </div>
              <div className="mb-3">
                <Tag color="blue">{formatWeekRange(c)}</Tag>
              </div>
              <Tooltip
                title={
                  already ? '已选择该课程' : full ? '课程容量已满' : conflict ? '与已选课程时间冲突' : undefined
                }
              >
              <Button
                type="primary"
                disabled={disabled}
                loading={mutation.isPending}
                onClick={() => {
                  if (already) return message.warning('已选择该课程');
                  if (full) return message.warning('课程容量已满');
                  if (conflict) return message.warning('与已选课程时间冲突');
                  mutation.mutate(c.id);
                }}
                block
              >
                {full ? '名额已满' : '选课程'}
              </Button>
              </Tooltip>
            </Card>
          );
        })}
      </div>
      <div className="flex justify-center mt-6">
        <Pagination
          current={page}
          onChange={setPage}
          pageSize={pageSize}
          total={filtered.length}
          showSizeChanger={false}
        />
      </div>

      {/* 教师信息Modal */}
      <Modal
        title={
          <div className="flex items-center">
            <UserOutlined className="mr-2 text-blue-500" />
            <span>教师信息</span>
          </div>
        }
        open={teacherModalVisible}
        onCancel={() => {
          setTeacherModalVisible(false);
          setSelectedTeacherName('');
        }}
        footer={null}
        width={600}
      >
        {teacherLoading ? (
          <div className="text-center py-8 text-gray-400">加载中...</div>
        ) : teacherInfo ? (
          <Descriptions column={1} bordered>
            <Descriptions.Item label={<span><UserOutlined className="mr-1" />姓名</span>}>
              {teacherInfo.name}
            </Descriptions.Item>
            <Descriptions.Item label={<span><TeamOutlined className="mr-1" />所属学院</span>}>
              {teacherInfo.college || '-'}
            </Descriptions.Item>
            <Descriptions.Item label={<span><TrophyOutlined className="mr-1" />职称</span>}>
              {teacherInfo.title || '-'}
            </Descriptions.Item>
            {teacherInfo.email && (
              <Descriptions.Item label={<span><MailOutlined className="mr-1" />邮箱</span>}>
                {teacherInfo.email}
              </Descriptions.Item>
            )}
            {teacherInfo.phone && (
              <Descriptions.Item label={<span><PhoneOutlined className="mr-1" />电话</span>}>
                {teacherInfo.phone}
              </Descriptions.Item>
            )}
            {teacherInfo.researchArea && (
              <Descriptions.Item label={<span><BookOutlined className="mr-1" />研究方向</span>}>
                {teacherInfo.researchArea}
              </Descriptions.Item>
            )}
            {teacherInfo.publishedPapers !== undefined && (
              <Descriptions.Item label="发表论文数">
                {teacherInfo.publishedPapers} 篇
              </Descriptions.Item>
            )}
            {teacherInfo.intro && (
              <Descriptions.Item label="个人简介">
                {teacherInfo.intro}
              </Descriptions.Item>
            )}
          </Descriptions>
        ) : (
          <div className="text-center py-8 text-gray-400">未找到教师信息</div>
        )}
      </Modal>
    </div>
  );
}

function formatWeekRange(course: any): string {
  let minStart: number | undefined;
  let maxEnd: number | undefined;
  for (const s of course.timeSlots || []) {
    if (s.weeks && s.weeks.length) {
      const wmin = Math.min(...s.weeks);
      const wmax = Math.max(...s.weeks);
      minStart = minStart === undefined ? wmin : Math.min(minStart, wmin);
      maxEnd = maxEnd === undefined ? wmax : Math.max(maxEnd, wmax);
    }
    if (s.startWeek !== undefined) {
      minStart = minStart === undefined ? s.startWeek : Math.min(minStart, s.startWeek);
    }
    if (s.endWeek !== undefined) {
      maxEnd = maxEnd === undefined ? s.endWeek : Math.max(maxEnd, s.endWeek);
    }
  }
  if (minStart !== undefined && maxEnd !== undefined) return `第${minStart}-${maxEnd}周`;
  return '周次待定';
}


